use fast_common::common::orm_config::RB;
use fast_common::models::menu::{Menu, MenuVo};


use rbatis::core::db::DBExecResult;
use rbatis::core::Result;
use rbatis::crud::CRUD;
use rbatis::DateTimeNative;
use rbatis::plugin::page::{Page, PageRequest};



pub struct MenuService {}

impl MenuService {
    pub async fn add(mut menu: Menu) -> Result<DBExecResult> {
        let id = 1 as u64;
        menu.menu_id = Some(id);
        menu.create_time = Some(DateTimeNative::now());
        let result = RB.save(&menu, &[]).await?;
        Ok(result)
    }

    pub async fn update(menu: Menu) -> Result<u64> {
        let wrapper = RB.new_wrapper();
        let result = RB.update_by_wrapper( &menu, wrapper, &[]).await;
        result
    }

    pub async fn delete(_menu: Menu) -> Result<u64> {
        let wrapper = RB.new_wrapper();
        RB.remove_by_wrapper::<Menu>(wrapper).await
    }

    pub async fn list(arg: MenuVo) -> Result<Page<Menu>> {
        let mut wrapper = RB.new_wrapper();
        if arg.menu_id.is_some() {
            wrapper = wrapper.eq("id", &arg.menu_id);
        }
        /* if arg.user_name.is_some() {
            wrapper = wrapper.like("%user_name%", &arg.user_name);
        }
        if arg.age.is_some() {
            wrapper = wrapper.eq("age", &arg.user_name);
        }*/
        if arg.create_time.is_some() {
            wrapper = wrapper.gt("create_time", arg.create_time);
        }

        let page_request = PageRequest::new(arg.page_num.unwrap(), arg.page_size.unwrap());
        let page = RB.fetch_page_by_wrapper(wrapper, &page_request).await;
        page
    }

    pub async fn _find_menus_by_role(role_id: u64) -> Result<Vec<Menu>> {
        let mut wrapper = RB.new_wrapper();
        wrapper = wrapper.do_if(false, |wrapper| wrapper.eq("role_id", role_id));
        let x = RB.fetch_list_by_wrapper::<Menu>(wrapper).await;
        x
    }
}
